<!DOCTYPE html>
<html>
<head>
<title>subscribe() is rejected when called with a different sender id</title>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<script src="../serviceworker/resources/test-helpers.js"></script>
</head>
<body>
<script>
async_test(function(test) {
    var workerUrl = 'resources/instrumentation-service-worker.js';
    var workerScope = 'resources/scope/' + location.pathname;
    var swRegistration;
    const FIRST_SENDER_ID_OPTIONS = {
        userVisibleOnly: true,
        applicationServerKey: new TextEncoder().encode('1234567890')
    };
    const SECOND_SENDER_ID_OPTIONS = {
        userVisibleOnly: true,
        applicationServerKey: new TextEncoder().encode('0987654321')
    };
    service_worker_unregister_and_register(test, workerUrl, workerScope)
        .then(function(serviceWorkerRegistration) {
            swRegistration = serviceWorkerRegistration;
            return wait_for_state(test, swRegistration.installing, 'activated');
        })
        .then(function() {
            // If running manually, grant permission when prompted.
            if (window.testRunner) {
                testRunner.setPermission('push-messaging', 'granted',
                    location.origin, location.origin);
            }
            return swRegistration.pushManager.subscribe(
                FIRST_SENDER_ID_OPTIONS);
        })
        .then(function(pushSubscription) {
            return swRegistration.pushManager.subscribe(
                SECOND_SENDER_ID_OPTIONS);
        })
        .then(function(pushSubscription) {
            assert_unreached(
                'Second subscribe() must not succeed with different sender ID');
        }, function(e) {
            assert_equals(e.name, 'InvalidStateError');
            assert_equals(e.message, 'Registration failed - ' +
                'A subscription with a different applicationServerKey ' +
                '(or gcm_sender_id) already exists; to change the ' +
                'applicationServerKey, unsubscribe then resubscribe.');
            return service_worker_unregister_and_done(test, workerScope);
        })
        .catch(unreached_rejection(test));
}, 'subscribe() is rejected when a subscription with a different sender ID' +
    'already exists');
</script>
</body>
</html>
